<extend name="Common@Layout:layui" />
<block name="title">
    <title>聊天记录</title>
</block>
<block name="style">
    <css href="/Public/res/css/layim.css" />
    <style>
    	::-webkit-scrollbar{width: 5px;}
        .dis{display: none;}
		.lxd-img{cursor: pointer;}
    </style>
</block>

<block name="main">
    <input type="hidden" id="touser" value="{$_GET['tid']}">
    <input type="hidden" id="myuid" value="{$_SESSION['loginUser']['uid']}">
    <input type="hidden" id="myname" value="{$_SESSION['loginUser']['username']}">
    <input type="hidden" id="myavatar" value="{$_SESSION['loginUser']['avater'] | default='/Public/res/images/avatar/default.png'}">
    <div class="layim-chat-main">
	    <div class="layim-chat-system look_more dis"><span layim-event="chatLog">查看更多记录</span></div>
        <ul></ul>
    </div>
    <script id="data-tpl" type="text/html">
        {{# layui.each(d, function(index, item){ }}
        <li {{# if(item.ismine==1 ) { }}class="layim-chat-mine" {{# } }}>
            <div class="layim-chat-user">
                <img src="{{item.user.portraitUri}}"> {{# if(item.ismine==1 ) { }}
                <cite><i>{{item.mtime}}</i>{{item.user.name}}</cite> {{# } }} {{# if(item.ismine==0 ) { }}
                <cite>{{item.user.name}}<i>{{item.mtime}}</i></cite> {{# } }}
            </div>
            <div class="layim-chat-text">{{item.content}}</div>
        </li>
        {{# }); }}
    </script>
</block>

<block name="script">
    <js href="http://cdn.ronghub.com/RongIMLib-2.2.5.min.js" />
    <script>
        layui.use(['jquery', 'layer', 'form', 'face', 'laytpl'], function() {
            var $ = layui.jquery,
                faces = layui.face,
                layer = layui.layer,
                laytpl = layui.laytpl,
                form = layui.form();

            var p = 1;
            var row = 20;
            var totalCount = 0;
            var domHeight = 0;
			var touid = $('#touser').val();
            var myinfo = {
                id: $('#myuid').val(),
                name: $('#myname').val(),
                portraitUri: $('#myavatar').val()
            };
            $(function($) {
            	p=1;
                get_message();
                $('.layim-chat-main').css('height', document.body.scrollHeight-30);
            });
			
			$('.look_more').click(function(){
				p++;
				get_message();
			});
			
			function listen_img_fangda(){
				$('.lxd-img').unbind('click').click(function(){
					layer.photos({
		                photos: '.layim-chat-text',
		                anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
		            });
				});
			}
			
			function get_message(){
				$.post('/Plugin/Chat/get_message',{"uid":myinfo.id,"touid":touid,"p":p,"row":row},function(ret){
					var $dataDom = $('.layim-chat-main ul');
	                var dataTpl = $('#data-tpl').html();
	                if(ret.status){
			            var datas = [];
	                	var data = ret.data.data;
	                	totalCount += data.length;
	                	var total = ret.data.total;
	                	if(totalCount != total){
	                		$('.layim-chat-system').removeClass('dis');
	                	}else{
	                		$('.layim-chat-system').addClass('dis');
	                	}
	                	for(var i=data.length-1; i>=0; i--){
	                		var ismine = 0;
	                		var user = {};
	                		if(data[i].uid == myinfo.id){
	                			ismine = 1;
	                		}
	                		user.name = data[i].username;
	                		user.portraitUri = data[i].avater?data[i].avater:'/Public/res/images/avatar/default.png';
	                		var dataSingle = {
			                    'ismine': ismine,
			                    'user': user,
			                    'mtime': data[i].send_time,
			                    'content': changeContent(data[i].content)
			                };
			                datas.push(dataSingle);
	                	}
	                	laytpl(dataTpl).render(datas, function(html) {
		                    if(p == 1){
	                			$dataDom.html(html);
			                    $('.layim-chat-main').scrollTop($dataDom.height());
			                    domHeight = $dataDom.height();
	                		}else{
	                			$dataDom.prepend(html);
	                			$('.layim-chat-main').scrollTop($dataDom.height() - domHeight);
			                    domHeight = $dataDom.height();
	                		} 
	                		listen_img_fangda();
		               });
	                }
	                
				});
			}

            function changeContent(content) {
                //支持的html标签
                var html = function(end) {
                    return new RegExp('\\[' + (end || '') + '(pre|div|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)\\]\\n*', 'g');
                };
                content = escape(content || '') //XSS
                    .replace(/img\[([^\s]+?)\]/g, function(img) { //转义图片
                        return '<img data-isbig="0" class="lxd-img" src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
                    }).replace(/@(\S+)(\s+?|$)/g, '@<a href="javascript:;" class="fly-aite">$1</a>$2') //转义@
                    .replace(/face\[([^\s\[\]]+?)\]/g, function(face) { //转义表情
                        var alt = face.replace(/^face/g, '');
                        return '<img alt="' + alt + '" title="' + alt + '" src="' + faces[alt] + '">';
                    }).replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function(str) { //转义链接
                        var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                        var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                        if (!href) return str;
                        var rel = /^(http(s)*:\/\/)\b(?!(\w+\.)*(sentsin.com|layui.com))\b/.test(href.replace(/\s/g, ''));
                        return '<a href="' + href + '" target="_blank"' + (rel ? ' rel="nofollow"' : '') + '>' + (text || href) + '</a>';
                    }).replace(html(), '\<$1\>').replace(html('/'), '\</$1\>') //转移代码
                    .replace(/\n/g, '<br>') //转义换行   
                return content;
            }

            function escape(html) {
                return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
                    .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
            }

            

            function formatDateTime(inputTime) {
                var date = new Date(inputTime);
                var y = date.getFullYear();
                var m = date.getMonth() + 1;
                m = m < 10 ? ('0' + m) : m;
                var d = date.getDate();
                d = d < 10 ? ('0' + d) : d;
                var h = date.getHours();
                h = h < 10 ? ('0' + h) : h;
                var minute = date.getMinutes();
                var second = date.getSeconds();
                minute = minute < 10 ? ('0' + minute) : minute;
                second = second < 10 ? ('0' + second) : second;
                return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
            };
        });
    </script>
</block>